package com.yjd.api.order;

import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.model.PagerModel;
import com.yjd.comm.enums.OrderShowStatusEnum;
import com.yjd.comm.enums.RepaymentReportStatus;
import com.yjd.comm.enums.StagesStatusEnum;
import com.yjd.comm.funds.model.RechargeOrderModel;
import com.yjd.comm.funds.service.IRechargeOrderService;
import com.yjd.comm.order.model.*;
import com.yjd.comm.order.service.IOrderProjectService;
import com.yjd.comm.order.service.IOrderService;
import com.yjd.comm.org.model.OrganizationModel;
import com.yjd.comm.org.service.IOrganizationService;
import com.yjd.comm.project.model.ProjectModel;
import com.yjd.comm.project.model.ProjectShowInfo;
import com.yjd.comm.project.service.IProjectService;
import com.yjd.comm.repayment.dto.OverdueDto;
import com.yjd.comm.repayment.enums.RepaymentStatusEnum;
import com.yjd.comm.repayment.model.RepaymentDataModel;
import com.yjd.comm.repayment.service.IRepaymentDataService;
import com.yjd.comm.system.model.SysParamModel;
import com.yjd.comm.system.util.SysParamUtil;
import com.yjd.comm.user.model.UserModel;
import com.yjd.comm.util.*;
import com.yjd.comm.vo.Constant;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.*;

/**
 * 订单相关操作
 * Created by yangchangyan on 2017/7/6.
 */
@Controller("com.yjd.api.order.OrderControl")
@Scope("prototype")
@RequestMapping("/order")
public class OrderControl extends BaseControl {
    @Resource
    IRepaymentDataService repaymentDataService;

    @Resource
    IOrderService orderService;

    @Resource
    IRechargeOrderService rechargeOrderService;

    @Resource
    IOrganizationService organizationService;

    @Resource
    IOrderProjectService orderProjectService;

    @Resource
    IProjectService projectService;

    /**
     * 获取还款信息:
     * 1、如果用户上一期未还（或者部分未还）计算罚息金额（未还金额+罚息），数据不入库。
     * 2、返回当期期数、应还本金、应还利息、罚息金额
     * <p>
     * Created by yangchangyan on 2017/7/6.
     *
     * @param order_id 订单id
     * @param period   当前还款期数
     * @return void
     * @throws
     */
    @RequestMapping(value = "/prerepayment", method = RequestMethod.POST)
    public void preRepayment(Long order_id, Integer period) throws Exception {
        if (null == order_id || null == period) {
            FrameUtil.throwBaseException1("信息错误。");
        }

        // 查询当期还款信息
        RepaymentDataModel repay = repaymentDataService.getModelOne(
                FrameUtil.newHashMap("order_id", order_id, "period", period), DbWREnums.WRITE);
        if (null == repay) {
            FrameUtil.throwBaseException1("订单不存在");
        }

        if (RepaymentStatusEnum.YES.getCode() == repay.getRepayment_status()) {
            this.successMsg("当期已还");
            return;
        }

        // 计算罚息金额
        OverdueDto overdueDto = RepaymentUtils.overdueInterest(repay.getRepayment_amount(), repay.getEstimation_repayment_time(), FrameUtil.getTime());
        Double overdue_price = overdueDto == null ? 0D : overdueDto.getOverduePrice();

        repay.getStrMap().put("period", repay.getPeriod());
        repay.getStrMap().put("capital", repay.getCapital());
        repay.getStrMap().put("interest", repay.getInterest());
        repay.getStrMap().put("discount_amount", repay.getDiscount_amount());
        repay.getStrMap().put("overdue_price", overdue_price);

        // 应还金额（应还本金+应还利息）
        Double repayment_amount = ArithUtil.adds(repay.getRepayment_amount(), repay.getCapital(), repay.getInterest());
        repay.getStrMap().put("repayment_amount", repayment_amount);
        // 实还金额（应还金额+罚息金额-减免金额）
        repay.getStrMap().put("repayment", ArithUtil.sub(ArithUtil.add(repayment_amount, overdue_price), repay.getDiscount_amount()));

        // 生成返回信息
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        paramMap.put("repaymentInfo", repay.getStrMap());
        this.successData(paramMap);
    }


        /**
         * 还款（扣款、更新还款记录）
         * Created by yangchangyan on 2017/7/6.
         *
         * @param repayment_id 还款报表id
         * @param pay_password 支付密码
         * @return void
         * @throws
         */
    @RequestMapping(value = "/repayment", method = RequestMethod.POST)
    public void repayment(Long repayment_id, String pay_password) throws Exception {

        UserModel user = super.getUserSession();
        validateRepayment(user,repayment_id,pay_password);//验证还款id
        this.repaymentDataService.repayment(repayment_id);
        this.successMsg("还款成功");
    }

    private boolean isCanceled(int orderStatus) {
        StagesStatusEnum currentStatus = StagesStatusEnum.parse(orderStatus);
        switch (currentStatus) {
//            case MERCHANT_CONFIRM_CANCEL:{return true;}
            case MYSEFL_CANCEL: {
                return true;
            }
            case MERCHANT_CANCEL: {
                return true;
            }
            default: {
                return false;
            }
        }
    }

    private List<String> getOderPics(Long Order_id) throws Exception {
        // 订单对应的项目id
        List<Long> projectIdList = orderProjectService.queryProjectId(FrameUtil.newHashMap("order_id", Order_id));

        //查询项目图片信息
        List<ProjectModel> projects = projectService.getModelList(
                FrameUtil.newHashMap("idList", projectIdList), DbWREnums.READ);

        List<String> pics = new ArrayList<String>();
        for (ProjectModel model : projects) {
            pics.add(ServletUtil.getFileUrl(model.getProject_pic()));
        }

        return pics;
    }

    private Map<Long, String> getPrjMap(List<ProjectModel> list) throws Exception {
        Map<Long, String> picsMap = new HashMap<Long, String>();
        for (ProjectModel model : list) {
            picsMap.put(model.getProject_id(), ServletUtil.getFileUrl(model.getProject_pic()));
        }
        return picsMap;
    }

    /**
     * 用户取消订单
     * @param order_id
     * @throws Exception
     */
    @RequestMapping(value = "/cancel", method = RequestMethod.POST)
    public void cancel(Long order_id) throws Exception {
        Long user_id = super.getSessionUserId();
        OrderModel orderModel = orderService.getModelById(order_id, DbWREnums.READ);
        if (orderModel == null) {
            FrameUtil.throwBaseException1("您的订单不存在");
        }

        if (orderModel.getUser_id().intValue() != user_id.intValue()) {
            FrameUtil.throwBaseException1("您操作的订单不属于您的");
        }
        orderService.myselfCanel(user_id, order_id);
        this.successMsg("您的订单取消申请成功");
    }

    /**
     *  新版1.4版本专用 ，老的接口继续留着兼容老版本
     * @throws Exception
     */
    @RequestMapping("/detail/v4")
    public void detail_V4(@RequestParam Long order_id) throws Exception {
        if (order_id == null) {
            FrameUtil.throwBaseException1("请求参数不能为空");
        }
        OrderModel orderModel = orderService.getModelById(order_id, DbWREnums.READ);
        if (orderModel == null) {
            FrameUtil.throwBaseException1("订单不存在");
        }

        Long user_id = getUserSession().getUser_id();
        if (orderModel.getUser_id().longValue() != user_id.longValue()) {
            FrameUtil.throwBaseException1("当前订单不属于您的订单");
        }

        if(orderModel.getFund_channel().intValue() > 1 && orderModel.getStatus().intValue() == StagesStatusEnum.REPAYMENTING.getCode()){
            // 如果资金走乾康且状态还在还款中则先查询第三方数据并更新本地
            repaymentDataService.updatePlanByOrder(orderModel, 0);
            orderModel = orderService.getModelById(order_id, DbWREnums.READ);//数据更新后查询查询一遍
        }

        List<OrderProjectModel> orderProjectModelList = orderProjectService.getModelList(FrameUtil.newHashMap("order_id", order_id), DbWREnums.READ);

        List<Long> projectIdList = new ArrayList<>();
        for (OrderProjectModel opm : orderProjectModelList) {
            projectIdList.add(opm.getProject_id());
        }
        //查询项目图片信息
        List<ProjectModel> projects = projectService.getModelList(
                FrameUtil.newHashMap("idList", projectIdList), DbWREnums.READ);
        Map<Long, String> prjPics = getPrjMap(projects);
        List<Long> prjIdList = FrameUtil.getBeanFieldValues(orderProjectModelList, "project_id");
        Map<Long, ProjectShowInfo> prjMap = projectService.getProjectInfoList(prjIdList);

        List<ProjectShowInfo> prjShowList = new ArrayList<ProjectShowInfo>();
        for (OrderProjectModel orderProjectModel : orderProjectModelList) {
            ProjectShowInfo projectShowInfo = prjMap.get(orderProjectModel.getProject_id());
            projectShowInfo.setPicsUrl(prjPics.get(projectShowInfo.getProject_id()));
            projectShowInfo.setProject_price(NumberUtil.formatNumber(orderProjectModel.getProject_price(), NumberUtil.FORMAT_4));
            projectShowInfo.setPayment(orderProjectModel.getPayment());
            projectShowInfo.setLoan_price(orderProjectModel.getLoan_price());
            prjShowList.add(projectShowInfo);
        }

        OrderDetailDto orderDetailDto = new OrderDetailDto();
        orderDetailDto.setFund_channel(orderModel.getFund_channel());
        orderDetailDto.setPayment(orderModel.getPayment());
        orderDetailDto.setLoan_price(orderModel.getLoan_amount());
        orderDetailDto.setOrder_id(order_id);
        orderDetailDto.setSum_price(NumberUtil.formatNumber(orderModel.getOrder_amount(), NumberUtil.FORMAT_4));
        orderDetailDto.setPrice(NumberUtil.formatNumber(orderModel.getLoan_amount(), NumberUtil.FORMAT_4));
        orderDetailDto.setPrjList(prjShowList);
        orderDetailDto.setLimit(orderModel.getPeriod());
        orderDetailDto.setLimit_curr(orderModel.getLimit_pay() + 1);
        Double limit_price = ArithUtil.round(ArithUtil.div(orderModel.getTotal_amount(), orderModel.getPeriod()));
        orderDetailDto.setLimit_price(NumberUtil.formatNumber(limit_price, NumberUtil.FORMAT_4));
        orderDetailDto.setOver_time(DateUtil.timestampToDateString(orderModel.getLast_update_time(), DateUtil.PATTERN_yyyy_MM_dd));
        orderDetailDto.setCancelable(0); //订单是否可以撤销 0：否 1是
        orderDetailDto.setOrder_no(orderModel.getOrder_no());
        //orderDetailDto.setOverdue_price(0D);
        //orderDetailDto.setOver_day(0);

        // 还款计划
        Map repaymentPlan = new HashMap();
        repaymentPlan.put("totalPeriod", orderModel.getPeriod());
        repaymentPlan.put("plans", Collections.EMPTY_LIST);
        orderDetailDto.setRepaymentPlan(repaymentPlan);

        //设置订单状态对应的显示状态
        OrderShowStatusEnum showStatusEnum = OrderShowStatusUtil.toOrderShowStatus(StagesStatusEnum.parse(orderModel.getStatus()));
        orderDetailDto.setShow_state(showStatusEnum.getLabel());
        orderDetailDto.setState(showStatusEnum.getCode());

        // 设置还款报表当前状态
        OrderShowStatusEnum repaymentShowStatus = OrderShowStatusUtil.toRepaymentShowStatus(null);
        orderDetailDto.setLimit_state(repaymentShowStatus.getCode());
        orderDetailDto.setShow_limit_state(repaymentShowStatus.getLabel());

        String valid_time = SysParamUtil.getValue(Constant.SysParamKeyEnum.MFQ_ORDER_VALID_TIME);
        Long currentTime = FrameUtil.getTime();

        //设置还款报表当前状态
        if(orderDetailDto.getState().intValue()==OrderShowStatusEnum.ODR_ACCEPT.getCode()){
            //订单状态受理中判断是否失效
            Long times = Long.parseLong(valid_time);
            if (currentTime.intValue() - times.intValue() > orderModel.getCreate_time().intValue()) {
                RechargeOrderModel recharge = rechargeOrderService.getModelOne(
                        FrameUtil.newHashMap("user_id", user_id, "order_type", "1", "ref_id", order_id, "status", "0"), DbWREnums.WRITE);
                if(null == recharge){
                    orderDetailDto.setShow_state(OrderShowStatusEnum.ODR_CANCEL.getLabel());
                    orderDetailDto.setState(OrderShowStatusEnum.ODR_CANCEL.getCode());
                }
            }
        }else if(orderDetailDto.getState().intValue()==OrderShowStatusEnum.ODR_REPAYMENTING.getCode()){
            //订单状态还款中处理
            List<RepaymentDataModel> allRepaymentDataModel = repaymentDataService.getModelList(
                    FrameUtil.newHashMap("order_id", orderModel.getOrder_id()), DbWREnums.READ);

            int nextRepaymentPeriod = orderModel.getLimit_pay() + 1;
            RepaymentDataModel repaymentDataModel = null;
            List<RepaymentPlanDto> plans = new ArrayList();
            RepaymentPlanDto plan = null;
            for(RepaymentDataModel rdm : allRepaymentDataModel){
                plan = new RepaymentPlanDto();
                plan.setPeriod(rdm.getPeriod());
                plan.setEstimation_repayment_time(DateUtil.timestampToDateString(rdm.getEstimation_repayment_time(), DateUtil.PATTERN_yyyy_MM_dd));
                plan.setRepayment_status(rdm.getRepayment_status());
                plans.add(plan);
                if(rdm.getPeriod().intValue() == nextRepaymentPeriod){
                    repaymentDataModel = rdm;
                }
            }

            // 还款计划
            repaymentPlan.put("plans", plans);

            orderDetailDto.setOver_time(DateUtil.timestampToDateString(repaymentDataModel.getEstimation_repayment_time(), DateUtil.PATTERN_yyyy_MM_dd));
            orderDetailDto.setRepayment_amount(repaymentDataModel.getRepayment_amount());
            orderDetailDto.setRepayment_id(repaymentDataModel.getId());

            // 已逾期
            if (repaymentDataModel.getEstimation_repayment_time().longValue() < currentTime) {
                orderDetailDto.setShow_limit_state(OrderShowStatusEnum.RPT_OVERDUE.getLabel());
                orderDetailDto.setLimit_state(OrderShowStatusEnum.RPT_OVERDUE.getCode());
                //计算罚息金额
                OverdueDto overdueDto = RepaymentUtils.overdueInterest(repaymentDataModel.getRepayment_amount(), repaymentDataModel.getEstimation_repayment_time(), FrameUtil.getTime());
                if(orderModel.getFund_channel().intValue() > 1){
                    overdueDto.setOverduePrice(repaymentDataModel.getOverdue_price());
                    overdueDto.setOverdueDay(repaymentDataModel.getOverdue_day());
                }
                if(orderModel.getFund_channel().intValue()==1){
                    //默认资金渠道平台计算罚息
                    if(overdueDto!=null&&overdueDto.getOverdueDay()>0){
                        Double overdue_price = overdueDto.getOverduePrice();
                        orderDetailDto.setLimit_price(NumberUtil.formatNumber(ArithUtil.sub(
                                ArithUtil.add(repaymentDataModel.getRepayment_amount(), overdue_price),
                                repaymentDataModel.getDiscount_amount()), NumberUtil.FORMAT_4));
                        orderDetailDto.setOverdue_price(overdue_price);
                        orderDetailDto.setOver_day(overdueDto.getOverdueDay());
                    }
                }else if(orderModel.getFund_channel().intValue() > 1){
                    //乾康资金处理
                    if(overdueDto!=null&&overdueDto.getOverdueDay()>0){
                        orderDetailDto.setOver_day(overdueDto.getOverdueDay());
                        orderDetailDto.setOverdue_price(overdueDto.getOverduePrice());
                    }
                }
            } else {
                // 前一期应还款时间（如果是第一期：返回第一期时间，如果大于第一期：返回前一期，月份-1的时间）
                Long prePeriodRepaymentTime = nextRepaymentPeriod - 1 < 1 ? repaymentDataModel.getEstimation_repayment_time() : DateUtil.addMonth(repaymentDataModel.getEstimation_repayment_time(), -1);
                if (currentTime < prePeriodRepaymentTime.longValue()) {
                    if (orderModel.getLimit_pay().intValue() == 0) {
                        // 当期未还清
                        orderDetailDto.setShow_limit_state(OrderShowStatusEnum.RPT_NONE_CLEAN.getLabel());
                        orderDetailDto.setLimit_state(OrderShowStatusEnum.RPT_NONE_CLEAN.getCode());
                        // 第一期未还清前，可以取消订单
                        if (repaymentDataModel.getPeriod() == 1) {
                            orderDetailDto.setCancelable(1);
                        }
                    } else {
                        // 当期已还清
                        orderDetailDto.setShow_limit_state(OrderShowStatusEnum.RPT_CLEAN.getLabel());
                        orderDetailDto.setLimit_state(OrderShowStatusEnum.RPT_CLEAN.getCode());
                    }
                } else {
                    // 当期未还清
                    orderDetailDto.setShow_limit_state(OrderShowStatusEnum.RPT_NONE_CLEAN.getLabel());
                    orderDetailDto.setLimit_state(OrderShowStatusEnum.RPT_NONE_CLEAN.getCode());
                    // 第一期未还清前，可以取消订单
                    if (repaymentDataModel.getPeriod() == 1) {
                        orderDetailDto.setCancelable(1);
                    }
                }
            }

        } else if(orderDetailDto.getState().intValue()==OrderShowStatusEnum.ODR_REPAYMENED.getCode()){

            // 还款计划
            List<RepaymentDataModel> allRepaymentDataModel = repaymentDataService.getModelList(
                    FrameUtil.newHashMap("order_id", orderModel.getOrder_id()), DbWREnums.READ);

            List<RepaymentPlanDto> plans = new ArrayList();
            RepaymentPlanDto plan = null;
            for(RepaymentDataModel rdm : allRepaymentDataModel){
                plan = new RepaymentPlanDto();
                plan.setPeriod(rdm.getPeriod());
                plan.setEstimation_repayment_time(DateUtil.timestampToDateString(rdm.getEstimation_repayment_time(), DateUtil.PATTERN_yyyy_MM_dd));
                plan.setRepayment_status(rdm.getRepayment_status());
                plans.add(plan);
            }

            repaymentPlan.put("plans", plans);

            orderDetailDto.setShow_limit_state(OrderShowStatusEnum.RPT_ALL_CLEAN.getLabel());
            orderDetailDto.setLimit_state(OrderShowStatusEnum.RPT_ALL_CLEAN.getCode());
        }


        // 还款开关控制 0 关闭还款功能 1 打开还款功能，在没有配置时默认为关闭状态
        SysParamModel sysParam = SysParamUtil.getSysParamModel(Constant.SysParamKeyEnum.REPAYMENT_SWITCH);
        String repayment_switch = null == sysParam ? "0" : sysParam.getParam_value();

        this.successData(FrameUtil.newHashMap("data", orderDetailDto, "repayment_switch", repayment_switch));
    }

    /**
     * 四期订单列表：根据剩余待还天数查询订单
     * Created by yangchangyan on 2017/11/14.
     *
     * @param
     * @return
     * @throws
     */
    @RequestMapping("/repayment/day/left")
    public void repaymentOrder(Integer days) throws Exception {
        Map<String, Object> paramMap = ServletUtil.getPageParameterMap(request);
        paramMap.put("user_id", getUserSession().getUser_id());
        List statusList = new ArrayList();
        statusList.add(StagesStatusEnum.APPLY_SUCCESS.getCode());
        statusList.add(StagesStatusEnum.REPAYMENTING.getCode());
        if(!paramMap.containsKey("rows")){
            // 没有指定则默认为10
            paramMap.put("rows", "10");
        }

        // 今天00:00:00的秒数
        Long startTime = DateUtil.getFristSecond(FrameUtil.getTime());
        if(days != null && days >= 0){
            if(days.intValue() == 15){
                statusList.remove(StagesStatusEnum.APPLY_SUCCESS.getCode());
            }
//            paramMap.put("estimation_repayment_time_gt", startTime);
            if(days > 0){
                paramMap.put("estimation_repayment_time_le", startTime + days*24*60*60);
            }
        }

        paramMap.put("statusList", statusList);

        // 订单未支付状态过期时间（秒）
        String valid_time = SysParamUtil.getValue(Constant.SysParamKeyEnum.MFQ_ORDER_VALID_TIME);

        // 不显示失效订单
        paramMap.put("excludeInvalidOrder", FrameUtil.getTime() - Long.valueOf(valid_time));

        List<OrderModel> orderModelList = orderService.queryRepaymentOrder(paramMap, DbWREnums.READ);

        List<OrderInfoDto> showList = repaymentOrderProcess(orderModelList, Long.valueOf(valid_time));

        // 排序
        Collections.sort(showList, new Comparator<OrderInfoDto>() {
            @Override
            public int compare(OrderInfoDto o1, OrderInfoDto o2) {
                if (o1.getLimit_state() == OrderShowStatusEnum.RPT_UNKNOWN.getCode()){
                    return -1;
                } else if (o2.getLimit_state() == OrderShowStatusEnum.RPT_UNKNOWN.getCode()){
                    return 1;
                } else if (o1.getLimit_state() == OrderShowStatusEnum.RPT_OVERDUE.getCode()){
                    return -1;
                } else if (o2.getLimit_state() == OrderShowStatusEnum.RPT_OVERDUE.getCode()){
                    return 1;
                } else if (o1.getLimit_state() == OrderShowStatusEnum.RPT_NONE_CLEAN.getCode()){
                    return -1;
                } else if (o2.getLimit_state() == OrderShowStatusEnum.RPT_NONE_CLEAN.getCode()){
                    return 1;
                }

                return 0;
            }
        });


        PagerModel pagerModel = new PagerModel();
        pagerModel.setDataList(showList);

        // 还款开关控制 0 关闭还款功能 1 打开还款功能，在没有配置时默认为关闭状态
        SysParamModel sysParam = SysParamUtil.getSysParamModel(Constant.SysParamKeyEnum.REPAYMENT_SWITCH);
        String repayment_switch = null == sysParam ? "0" : sysParam.getParam_value();
        this.successData(FrameUtil.newHashMap("data", pagerModel, "repayment_switch", repayment_switch, "valid_time", valid_time));
    }

    /**
     * 四期订单列表：其他订单
     * Created by yangchangyan on 2017/11/14.
     * type 1：处理中（默认） 2：已完成
     *
     * @param
     * @return
     * @throws
     */
    @RequestMapping("/repayment/other")
    public void repaymentOrderOther(Integer type) throws Exception {
        Map<String, Object> paramMap = ServletUtil.getPageParameterMap(request);
        paramMap.put("user_id", getUserSession().getUser_id());

        // 订单未支付状态过期时间（秒）
        String valid_time = SysParamUtil.getValue(Constant.SysParamKeyEnum.MFQ_ORDER_VALID_TIME);

        List statusList = new ArrayList();
        if(null == type || type.intValue() == 1 ){
            statusList.add(StagesStatusEnum.MERCHANT_HANDING.getCode());
            statusList.add(StagesStatusEnum.MERCHANT_CONFIRM_CANCEL.getCode());
            statusList.add(StagesStatusEnum.LOAN_APPLY.getCode());
            paramMap.put("statusList", statusList);

            // 显示支付还没有到账的订单
            paramMap.put("includeRepaymentingOrder", FrameUtil.getTime() - Long.valueOf(valid_time));
        } else {
            statusList.add(StagesStatusEnum.INVALID.getCode());
            statusList.add(StagesStatusEnum.REPAYMENED.getCode());
            statusList.add(StagesStatusEnum.MERCHANT_REFUSAL.getCode());
            statusList.add(StagesStatusEnum.MYSEFL_CANCEL.getCode());
            statusList.add(StagesStatusEnum.MERCHANT_CANCEL.getCode());
            statusList.add(StagesStatusEnum.FUND_REFUSE.getCode());
            paramMap.put("statusList", statusList);

            // 显示失效订单（不包含支付还没有到账的订单）
            paramMap.put("includeInvalidOrder", FrameUtil.getTime() - Long.valueOf(valid_time));
        }
        paramMap.put("sort", " create_time desc ");
        if(!paramMap.containsKey("rows")){
            // 没有指定则默认为10
            paramMap.put("rows", "10");
        }

        PagerModel pagerModel = orderService.getPageModel(paramMap, DbWREnums.READ);

        List<OrderModel> orderModelList = pagerModel.getDataList();

        List<OrderInfoDto> showList = repaymentOrderProcess(orderModelList, Long.valueOf(valid_time));

        // type=1 处理中的，还没有到账的订单，显示状态为新状态支付中
        if(null == type || type.intValue() == 1 ){
            for(OrderInfoDto dto : showList){
                if(dto.getLimit_state() == RepaymentReportStatus.ORDER_INVALID.getCode()){
                    dto.setShow_state(RepaymentReportStatus.ORDER_PAYMENTING.getLabel());
                    dto.setLimit_state(RepaymentReportStatus.ORDER_PAYMENTING.getCode());
                }
            }
        }

        pagerModel.setDataList(showList);

        // 还款开关控制 0 关闭还款功能 1 打开还款功能，在没有配置时默认为关闭状态
        String repayment_switch = "0";
        this.successData(FrameUtil.newHashMap("data", pagerModel, "repayment_switch", repayment_switch, "valid_time", valid_time));
    }

    /**
     * 处理返回的订单信息
     * @param orderModelList
     * @param valid_time
     * @return
     * @throws Exception
     */
    private List<OrderInfoDto> repaymentOrderProcess(List<OrderModel> orderModelList, long valid_time) throws Exception {
        Long currentTime = FrameUtil.getTime();
        List<OrderInfoDto> showList = new ArrayList<OrderInfoDto>();

        Map<Long, String> orgMap = new HashMap<>();
        if(null != orderModelList && orderModelList.size() > 0){
            //查询机构相关信息
            orgMap = organizationService.allOrgAndName();
        }

        Iterator<OrderModel> iterator = orderModelList.iterator();
        OrderModel orderModel = null;
        while (iterator.hasNext()){
            orderModel = iterator.next();

            // 先更新一下还款报表的状态 （目前采取异步处理的方式更新）
//            List updateResult = repaymentDataService.updatePlanByOrder(orderModel, 0);
//            if(updateResult != null && updateResult.size() > 0){
//                // 还款报表有更新，说明状态可能有变化，则重新查询一遍订单信息
//                orderModel = orderService.getModelById(orderModel.getOrder_id(), DbWREnums.READ);
//            }

            OrderInfoDto orderInfoDto = new OrderInfoDto();
            orderInfoDto.setFund_channel(orderModel.getFund_channel());
            orderInfoDto.setOrder_time(orderModel.getCreate_time());
            orderInfoDto.setOrder_id(orderModel.getOrder_id());
            orderInfoDto.setLimit(orderModel.getPeriod());
            orderInfoDto.setLimit_curr(orderModel.getLimit_pay() + 1);
            orderInfoDto.setSum_price(NumberUtil.formatNumber(orderModel.getOrder_amount(), NumberUtil.FORMAT_4));
            orderInfoDto.setPicsUrlList(getOderPics(orderModel.getOrder_id()));
            orderInfoDto.setCancelable(0); //订单是否可以撤销 0：否 1是
            orderInfoDto.setOrder_no(orderModel.getOrder_no());
            orderInfoDto.setOverdue_price(0D);
            orderInfoDto.setRepayment_amount(0D);
            orderInfoDto.setPayment(orderModel.getPayment());
            orderInfoDto.setLoan_price(orderModel.getLoan_amount());
            if (null != orgMap.get(orderModel.getOrg_id())) {
                orderInfoDto.setOrg_name(orgMap.get(orderModel.getOrg_id()));
            }

            // 还款计划
            Map repaymentPlan = new HashMap();
            repaymentPlan.put("totalPeriod", orderModel.getPeriod());
            repaymentPlan.put("plans", Collections.EMPTY_LIST);
            orderInfoDto.setRepaymentPlan(repaymentPlan);

            orderInfoDto.setOver_time(DateUtil.timestampToDateString(orderModel.getLast_update_time(), DateUtil.PATTERN_yyyy_MM_dd));

            // 当前订单状态
            StagesStatusEnum currentOrderStatus = StagesStatusEnum.parse(orderModel.getStatus());

            // 转换订单状态为用户显示状态
            OrderShowStatusEnum orderShowStatus = OrderShowStatusUtil.toOrderShowStatus(currentOrderStatus);
            orderInfoDto.setState(orderShowStatus.getCode());
            orderInfoDto.setShow_state(orderShowStatus.getLabel());

            // 设置还款报表当前状态
            OrderShowStatusEnum repaymentShowStatus = OrderShowStatusUtil.toRepaymentShowStatus(null);
            orderInfoDto.setLimit_state(repaymentShowStatus.getCode());
            orderInfoDto.setShow_limit_state(repaymentShowStatus.getLabel());
            if(orderInfoDto.getState() == OrderShowStatusEnum.ODR_ACCEPT.getCode()){
                Double limit_price = ArithUtil.round(ArithUtil.div(orderModel.getTotal_amount(), orderModel.getPeriod()));
                orderInfoDto.setLimit_price(NumberUtil.formatNumber(limit_price, NumberUtil.FORMAT_4));
                orderInfoDto.setCancelable(1);

                if (currentTime.longValue() - valid_time > orderModel.getCreate_time().longValue()) {
                    orderInfoDto.setCancelable(0);
                }
            }else if(orderInfoDto.getState() == OrderShowStatusEnum.ODR_REPAYMENTING.getCode()){

                //订单状态还款中处理
                List<RepaymentDataModel> allRepaymentDataModel = repaymentDataService.getModelList(
                        FrameUtil.newHashMap("order_id", orderModel.getOrder_id()), DbWREnums.READ);

                int period = orderModel.getLimit_pay() + 1;
                RepaymentDataModel repaymentDataModel = null;
                List<RepaymentPlanDto> plans = new ArrayList();
                RepaymentPlanDto plan = null;
                for(RepaymentDataModel rdm : allRepaymentDataModel){
                    plan = new RepaymentPlanDto();
                    plan.setPeriod(rdm.getPeriod());
                    plan.setEstimation_repayment_time(DateUtil.timestampToDateString(rdm.getEstimation_repayment_time(), DateUtil.PATTERN_yyyy_MM_dd));
                    plan.setRepayment_status(rdm.getRepayment_status());
                    plans.add(plan);
                    if(rdm.getPeriod().intValue() == period){
                        repaymentDataModel = rdm;
                    }
                }

                // 还款计划
                repaymentPlan.put("plans", plans);

                orderInfoDto.setOver_time(DateUtil.timestampToDateString(repaymentDataModel.getEstimation_repayment_time(), DateUtil.PATTERN_yyyy_MM_dd));

                // 计算罚息金额
                OverdueDto overdueDto = RepaymentUtils.overdueInterest(repaymentDataModel.getRepayment_amount(), repaymentDataModel.getEstimation_repayment_time(), FrameUtil.getTime());
                if(orderModel.getFund_channel().intValue() > 1){
                    overdueDto.setOverduePrice(repaymentDataModel.getOverdue_price());
                    overdueDto.setOverdueDay(repaymentDataModel.getOverdue_day());
                }
                orderInfoDto.setOver_day(overdueDto.getOverdueDay());
                orderInfoDto.setOverdue_price(overdueDto.getOverduePrice());
                orderInfoDto.setRepayment_amount(repaymentDataModel.getRepayment_amount());
                orderInfoDto.setLimit_price(NumberUtil.formatNumber(ArithUtil.sub(
                        ArithUtil.add(repaymentDataModel.getRepayment_amount(), overdueDto.getOverduePrice()),
                        repaymentDataModel.getDiscount_amount()), NumberUtil.FORMAT_4));
                orderInfoDto.setOver_time(DateUtil.timestampToDateString(repaymentDataModel.getEstimation_repayment_time(), DateUtil.PATTERN_yyyy_MM_dd));
                orderInfoDto.setDiscount_amount(NumberUtil.formatNumber(repaymentDataModel.getDiscount_amount(), NumberUtil.FORMAT_4));
                orderInfoDto.setRepayment_id(repaymentDataModel.getId());

                // 已逾期
                if (repaymentDataModel.getEstimation_repayment_time().longValue() < currentTime) {
                    orderInfoDto.setLimit_state(OrderShowStatusEnum.RPT_OVERDUE.getCode());
                    orderInfoDto.setShow_limit_state(OrderShowStatusEnum.RPT_OVERDUE.getLabel());
                }
                // 没有逾期
                else {
                    // 前一期应还款时间（如果是第一期：返回第一期时间，如果大于第一期：返回前一期，月份-1的时间）
                    Long prePeriodRepaymentTime = period - 1 < 1 ? repaymentDataModel.getEstimation_repayment_time() : DateUtil.addMonth(repaymentDataModel.getEstimation_repayment_time(), -1);
                    repaymentShowStatus = OrderShowStatusEnum.RPT_NONE_CLEAN;
                    if (currentTime < prePeriodRepaymentTime.longValue()) {
                        if (orderModel.getLimit_pay().intValue() == 0) {
                            // 当期未还清
                            orderInfoDto.setLimit_state(repaymentShowStatus.getCode());
                            orderInfoDto.setShow_limit_state(repaymentShowStatus.getLabel());
                            // 第一期未还清前，可以取消订单
                            if (repaymentDataModel.getPeriod() == 1) {
                                orderInfoDto.setCancelable(1);
                            }
                        } else {
                            // 当期已还清
                            repaymentShowStatus = OrderShowStatusEnum.RPT_CLEAN;
                            orderInfoDto.setLimit_state(repaymentShowStatus.getCode());
                            orderInfoDto.setShow_limit_state(repaymentShowStatus.getLabel());
                            prePeriodRepaymentTime = prePeriodRepaymentTime + DateUtil.DAY_IN_SECOND;
                            orderInfoDto.setStartRepaymenttime(DateUtil.timestampToDateString(prePeriodRepaymentTime, DateUtil.PATTERN_yyyy_MM_dd));
                        }
                    } else {
                        // 当期未还清
                        orderInfoDto.setLimit_state(repaymentShowStatus.getCode());
                        orderInfoDto.setShow_limit_state(repaymentShowStatus.getLabel());
                        // 第一期未还清前，可以取消订单
                        if (repaymentDataModel.getPeriod() == 1) {
                            orderInfoDto.setCancelable(1);
                        }
                    }
                }

            } else if(orderInfoDto.getState() == OrderShowStatusEnum.ODR_REPAYMENED.getCode()){

                // 还款计划
                List<RepaymentDataModel> allRepaymentDataModel = repaymentDataService.getModelList(
                        FrameUtil.newHashMap("order_id", orderModel.getOrder_id()), DbWREnums.READ);

                List<RepaymentPlanDto> plans = new ArrayList();
                RepaymentPlanDto plan = null;
                for(RepaymentDataModel rdm : allRepaymentDataModel){
                    plan = new RepaymentPlanDto();
                    plan.setPeriod(rdm.getPeriod());
                    plan.setEstimation_repayment_time(DateUtil.timestampToDateString(rdm.getEstimation_repayment_time(), DateUtil.PATTERN_yyyy_MM_dd));
                    plan.setRepayment_status(rdm.getRepayment_status());
                    plans.add(plan);
                }

                repaymentPlan.put("plans", plans);

                orderInfoDto.setShow_limit_state(OrderShowStatusEnum.RPT_ALL_CLEAN.getLabel());
                orderInfoDto.setLimit_state(OrderShowStatusEnum.RPT_ALL_CLEAN.getCode());
            }

            showList.add(orderInfoDto);
        }

        return showList;
    }

    private void  validateRepayment( UserModel user,Long repayment_id, String pay_password)throws Exception{
        // 验证支付密码
        String userPayPwd = SecurityCode.passwordMD5(pay_password.trim(), user.getEncrypt());
        String dbpwd = user.getPay_password();
        if (!(userPayPwd.equals(dbpwd))) {
            this.errorMsg("交易密码不正确");
            return;
        }

        // 查询当期还款信息
        RepaymentDataModel repay = repaymentDataService.getModelById(repayment_id, DbWREnums.READ);
        if (null == repay) {
            FrameUtil.throwBaseException1("您的还款报表不存在");
        }

        OrderModel orderModel = orderService.getModelById(repay.getOrder_id(), DbWREnums.READ);
        if (orderModel == null) {
            FrameUtil.throwBaseException1("您的还款订单不存在");
        }


        if (RepaymentStatusEnum.YES.getCode() == repay.getRepayment_status()) {
            this.successMsg("当期已还");
            return;
        }

        if (!(orderModel.getUser_id().toString().equals(user.getUser_id().toString()))) {
            this.errorMsg("当前还款不属于您的");
            return;
        }
    }

    /**
     *  新版1.3版本专用 ，老的接口继续留着兼容老版本
     * @throws Exception
     */
    @RequestMapping("/list1")
    public void list1() throws Exception {
        Map<String, Object> paramMap = ServletUtil.getPageParameterMap(request);
        Long user_id = getUserSession().getUser_id();
        paramMap.put("user_id", user_id);
        paramMap.put("sort", " create_time desc ");
        paramMap.put("rows", "10");
        PagerModel pagerModel = orderService.getPageModel(paramMap, DbWREnums.READ);
        List<OrderInfoDto> showList = new ArrayList<OrderInfoDto>();
        List<OrderModel> orderModelList = pagerModel.getDataList();
        String valid_time = SysParamUtil.getValue(Constant.SysParamKeyEnum.MFQ_ORDER_VALID_TIME);
        Long currentTime = FrameUtil.getTime();
        if (orderModelList != null && orderModelList.size() > 0) {
            List<Long> orgIdList = FrameUtil.getBeanFieldValues(orderModelList, "org_id");
            //查询机构相关信息
            Map<Long, OrganizationModel> orgMap = organizationService.getModelMapByIds(orgIdList, DbWREnums.READ);

            for (OrderModel orderModel : orderModelList) {
                OrderInfoDto orderInfoDto = new OrderInfoDto();
                orderInfoDto.setOrder_time(orderModel.getCreate_time());
                orderInfoDto.setOrder_id(orderModel.getOrder_id());
                orderInfoDto.setLimit(orderModel.getPeriod());
                orderInfoDto.setLimit_curr(orderModel.getLimit_pay() + 1);
                orderInfoDto.setSum_price(NumberUtil.formatNumber(orderModel.getOrder_amount(), NumberUtil.FORMAT_4));
                orderInfoDto.setPicsUrlList(getOderPics(orderModel.getOrder_id()));
                orderInfoDto.setCancelable(0); //订单是否可以撤销 0：否 1是
                orderInfoDto.setOrder_no(orderModel.getOrder_no());
                orderInfoDto.setOverdue_price(0D);
                orderInfoDto.setRepayment_amount(0D);
                orderInfoDto.setPayment(orderModel.getPayment());
                orderInfoDto.setLoan_price(orderModel.getLoan_amount());
                OrganizationModel organizationModel = orgMap.get(orderModel.getOrg_id());
                if (organizationModel != null) {
                    orderInfoDto.setOrg_name(organizationModel.getOrg_name());
                }

                // 如果订单被取消了，则标记为取消状态
                if (isCanceled(orderModel.getStatus())) {
                    orderInfoDto.setShow_state(StagesStatusEnum.parse(orderModel.getStatus()).getLabel());
                    orderInfoDto.setLimit_state(StagesStatusEnum.parse(orderModel.getStatus()).getCode());
                    orderInfoDto.setOver_time(DateUtil.timestampToDateString(orderModel.getLast_update_time(), DateUtil.PATTERN_yyyy_MM_dd));
                    showList.add(orderInfoDto);
                    continue;
                }

                // 订单已失效
                if (StagesStatusEnum.INVALID.getCode() == orderModel.getStatus()) {
                    orderInfoDto.setShow_state(StagesStatusEnum.MYSEFL_CANCEL.getLabel());
                    orderInfoDto.setLimit_state(StagesStatusEnum.MYSEFL_CANCEL.getCode());
                    orderInfoDto.setOver_time(DateUtil.timestampToDateString(orderModel.getLast_update_time(), DateUtil.PATTERN_yyyy_MM_dd));
                    showList.add(orderInfoDto);
                    continue;
                }

                // 商户拒绝
                if (StagesStatusEnum.MERCHANT_REFUSAL.getCode() == orderModel.getStatus()) {
                    orderInfoDto.setShow_state(StagesStatusEnum.MERCHANT_CANCEL.getLabel());
                    orderInfoDto.setLimit_state(StagesStatusEnum.MERCHANT_CANCEL.getCode());
                    orderInfoDto.setOver_time(DateUtil.timestampToDateString(orderModel.getLast_update_time(), DateUtil.PATTERN_yyyy_MM_dd));
                    showList.add(orderInfoDto);
                    continue;
                }

                // 订单已提交(首付款还没有支付)
                if (StagesStatusEnum.APPLY_SUCCESS.getCode() == orderModel.getStatus()) {
                    Double limit_price = ArithUtil.round(ArithUtil.div(orderModel.getTotal_amount(), orderModel.getPeriod()));
                    orderInfoDto.setLimit_price(NumberUtil.formatNumber(limit_price, NumberUtil.FORMAT_4));
                    orderInfoDto.setShow_state(RepaymentReportStatus.PAYMENT_INPROGRESS.getLabel());
                    orderInfoDto.setLimit_state(RepaymentReportStatus.PAYMENT_INPROGRESS.getCode());
                    orderInfoDto.setCancelable(1);

                    Long times = Long.parseLong(valid_time);
                    if (currentTime.intValue() - times.intValue() > orderModel.getCreate_time().intValue()) {
                        orderInfoDto.setShow_state(RepaymentReportStatus.ORDER_INVALID.getLabel());
                        orderInfoDto.setLimit_state(RepaymentReportStatus.ORDER_INVALID.getCode());
                        orderInfoDto.setCancelable(0);
                    }
                    orderInfoDto.setOver_time(DateUtil.timestampToDateString(orderModel.getLast_update_time(), DateUtil.PATTERN_yyyy_MM_dd));
                    showList.add(orderInfoDto);
                    continue;
                }

                // 订单处理中
                if (StagesStatusEnum.MERCHANT_HANDING.getCode() == orderModel.getStatus()) {
                    Double limit_price = ArithUtil.round(ArithUtil.div(orderModel.getTotal_amount(), orderModel.getPeriod()));
                    orderInfoDto.setLimit_price(NumberUtil.formatNumber(limit_price, NumberUtil.FORMAT_4));
                    orderInfoDto.setShow_state(RepaymentReportStatus.APPLY_SUCCESS.getLabel());
                    orderInfoDto.setLimit_state(RepaymentReportStatus.APPLY_SUCCESS.getCode());
                    orderInfoDto.setOver_time(DateUtil.timestampToDateString(orderModel.getLast_update_time(), DateUtil.PATTERN_yyyy_MM_dd));
                    orderInfoDto.setCancelable(1);
                    showList.add(orderInfoDto);
                    continue;
                }

                // 订单已结清
                if (orderModel.getPeriod().intValue() == orderModel.getLimit_pay().intValue()) {
                    orderInfoDto.setShow_state(RepaymentReportStatus.ALL_CLEAN.getLabel());
                    orderInfoDto.setLimit_state(RepaymentReportStatus.ALL_CLEAN.getCode());
                    orderInfoDto.setOver_time(DateUtil.timestampToDateString(orderModel.getLast_update_time(), DateUtil.PATTERN_yyyy_MM_dd));
                    showList.add(orderInfoDto);
                    continue;
                }

                int period = orderModel.getLimit_pay() + 1;
                repaymentDataService.updatePlanByOrder(orderModel, period);
                RepaymentDataModel repaymentDataModel = repaymentDataService.getModelOne(
                        FrameUtil.newHashMap("order_id", orderModel.getOrder_id(), "period", period), DbWREnums.READ);

                // 计算罚息金额
                OverdueDto overdueDto = RepaymentUtils.overdueInterest(repaymentDataModel.getRepayment_amount(), repaymentDataModel.getEstimation_repayment_time(), FrameUtil.getTime());
                Double overdue_price = overdueDto.getOverduePrice();

                orderInfoDto.setOverdue_price(overdue_price);
                orderInfoDto.setRepayment_amount(repaymentDataModel.getRepayment_amount());
                orderInfoDto.setLimit_price(NumberUtil.formatNumber(ArithUtil.sub(
                        ArithUtil.add(repaymentDataModel.getRepayment_amount(), overdue_price),
                        repaymentDataModel.getDiscount_amount()), NumberUtil.FORMAT_4));
                orderInfoDto.setOver_time(DateUtil.timestampToDateString(repaymentDataModel.getEstimation_repayment_time(), DateUtil.PATTERN_yyyy_MM_dd));
                orderInfoDto.setDiscount_amount(NumberUtil.formatNumber(repaymentDataModel.getDiscount_amount(), NumberUtil.FORMAT_4));
                orderInfoDto.setRepayment_id(repaymentDataModel.getId());

                // 取消受理中
                if (StagesStatusEnum.MERCHANT_CONFIRM_CANCEL.getCode() == orderModel.getStatus()) {
                    orderInfoDto.setLimit_state(StagesStatusEnum.MERCHANT_CONFIRM_CANCEL.getCode());
                    orderInfoDto.setShow_state(StagesStatusEnum.MERCHANT_CONFIRM_CANCEL.getLabel());
                    showList.add(orderInfoDto);
                    continue;
                }

                // 已逾期
                if (repaymentDataModel.getEstimation_repayment_time().longValue() < currentTime) {
                    orderInfoDto.setLimit_state(RepaymentReportStatus.OVERDUE.getCode());
                    orderInfoDto.setShow_state(RepaymentReportStatus.OVERDUE.getLabel());
                    showList.add(orderInfoDto);
                    continue;
                }

                // 前一期应还款时间（如果是第一期：返回第一期时间，如果大于第一期：返回前一期，月份-1的时间）
                Long prePeriodRepaymentTime = period - 1 < 1 ? repaymentDataModel.getEstimation_repayment_time() : DateUtil.addMonth(repaymentDataModel.getEstimation_repayment_time(), -1);

                if (currentTime < prePeriodRepaymentTime.longValue()) {
                    if (orderModel.getLimit_pay().intValue() == 0) {
                        // 当期未还清
                        orderInfoDto.setLimit_state(RepaymentReportStatus.PERIORD_NONE_CLEAN.getCode());
                        orderInfoDto.setShow_state(RepaymentReportStatus.PERIORD_NONE_CLEAN.getLabel());
                        // 第一期未还清前，可以取消订单
                        if (repaymentDataModel.getPeriod() == 1) {
                            orderInfoDto.setCancelable(1);
                        }
                    } else {
                        // 当期已还清
                        orderInfoDto.setShow_state(RepaymentReportStatus.PERIORD_CLEAN.getLabel());
                        orderInfoDto.setLimit_state(RepaymentReportStatus.PERIORD_CLEAN.getCode());
                    }
                } else {
                    // 当期未还清
                    orderInfoDto.setLimit_state(RepaymentReportStatus.PERIORD_NONE_CLEAN.getCode());
                    orderInfoDto.setShow_state(RepaymentReportStatus.PERIORD_NONE_CLEAN.getLabel());
                    // 第一期未还清前，可以取消订单
                    if (repaymentDataModel.getPeriod() == 1) {
                        orderInfoDto.setCancelable(1);
                    }
                }

                showList.add(orderInfoDto);
            }
        }
        pagerModel.setDataList(showList);

        // 还款开关控制 0 关闭还款功能 1 打开还款功能，在没有配置时默认为关闭状态
        SysParamModel sysParam = SysParamUtil.getSysParamModel(Constant.SysParamKeyEnum.REPAYMENT_SWITCH);
        String repayment_switch = null == sysParam ? "0" : sysParam.getParam_value();
        this.successData(FrameUtil.newHashMap("data", pagerModel, "repayment_switch", repayment_switch, "valid_time", valid_time));
    }

    /**
     *  新版1.3版本专用 ，老的接口继续留着兼容老版本
     * @throws Exception
     */
    @RequestMapping("/detail1")
    public void detail1(@RequestParam Long order_id) throws Exception {
        if (order_id == null) {
            FrameUtil.throwBaseException1("请求参数不能为空");
        }
        OrderModel orderModel = orderService.getModelById(order_id, DbWREnums.READ);
        if (orderModel == null) {
            FrameUtil.throwBaseException1("订单不存在");
        }

        Long user_id = getUserSession().getUser_id();
        if (orderModel.getUser_id().longValue() != user_id.longValue()) {
            FrameUtil.throwBaseException1("当前订单不属于您的订单");
        }

        List<OrderProjectModel> orderProjectModelList = orderProjectService.getModelList(FrameUtil.newHashMap("order_id", order_id), DbWREnums.READ);

        List<Long> projectIdList = new ArrayList<>();
        for (OrderProjectModel opm : orderProjectModelList) {
            projectIdList.add(opm.getProject_id());
        }
        //查询项目图片信息
        List<ProjectModel> projects = projectService.getModelList(
                FrameUtil.newHashMap("idList", projectIdList), DbWREnums.READ);
        Map<Long, String> prjPics = getPrjMap(projects);
        List<Long> prjIdList = FrameUtil.getBeanFieldValues(orderProjectModelList, "project_id");
        Map<Long, ProjectShowInfo> prjMap = projectService.getProjectInfoList(prjIdList);

        List<ProjectShowInfo> prjShowList = new ArrayList<ProjectShowInfo>();
        for (OrderProjectModel orderProjectModel : orderProjectModelList) {
            ProjectShowInfo projectShowInfo = prjMap.get(orderProjectModel.getProject_id());
            projectShowInfo.setPicsUrl(prjPics.get(projectShowInfo.getProject_id()));
            projectShowInfo.setProject_price(NumberUtil.formatNumber(orderProjectModel.getProject_price(), NumberUtil.FORMAT_4));
            projectShowInfo.setPayment(orderProjectModel.getPayment());
            projectShowInfo.setLoan_price(orderProjectModel.getLoan_price());
            prjShowList.add(projectShowInfo);
        }

        OrderDetailDto orderDetailDto = new OrderDetailDto();
        orderDetailDto.setPayment(orderModel.getPayment());
        orderDetailDto.setLoan_price(orderModel.getLoan_amount());
        orderDetailDto.setOrder_id(order_id);
        orderDetailDto.setSum_price(NumberUtil.formatNumber(orderModel.getOrder_amount(), NumberUtil.FORMAT_4));
        orderDetailDto.setPrice(NumberUtil.formatNumber(orderModel.getLoan_amount(), NumberUtil.FORMAT_4));
        orderDetailDto.setPrjList(prjShowList);
        orderDetailDto.setLimit(orderModel.getPeriod());
        orderDetailDto.setLimit_curr(orderModel.getLimit_pay() + 1);
        orderDetailDto.setLimit_price("0");
        orderDetailDto.setOver_time(DateUtil.timestampToDateString(orderModel.getLast_update_time(), DateUtil.PATTERN_yyyy_MM_dd));
        orderDetailDto.setState(orderModel.getStatus());
        orderDetailDto.setCancelable(0); //订单是否可以撤销 0：否 1是
        orderDetailDto.setOrder_no(orderModel.getOrder_no());
        orderDetailDto.setOverdue_price(0D);
        orderDetailDto.setOver_day(0);

        // 如果订单被取消了，则标记为取消状态
        if (isCanceled(orderModel.getStatus())) {
            orderDetailDto.setLimit_state(StagesStatusEnum.parse(orderModel.getStatus()).getCode());
            this.successData(FrameUtil.newHashMap("data", orderDetailDto));
            return;
        }

        // 订单已失效
        if (StagesStatusEnum.INVALID.getCode() == orderModel.getStatus()) {
            orderDetailDto.setLimit_state(StagesStatusEnum.MYSEFL_CANCEL.getCode());
            this.successData(FrameUtil.newHashMap("data", orderDetailDto));
            return;
        }

        // 商户拒绝
        if (StagesStatusEnum.MERCHANT_REFUSAL.getCode() == orderModel.getStatus()) {
            orderDetailDto.setLimit_state(StagesStatusEnum.MERCHANT_CANCEL.getCode());
            this.successData(FrameUtil.newHashMap("data", orderDetailDto));
            return;
        }

        String valid_time = SysParamUtil.getValue(Constant.SysParamKeyEnum.MFQ_ORDER_VALID_TIME);
        Long currentTime = FrameUtil.getTime();

        // 订单已提交(首付款还没有支付)
        if (StagesStatusEnum.APPLY_SUCCESS.getCode() == orderModel.getStatus()) {
            Double limit_price = ArithUtil.round(ArithUtil.div(orderModel.getTotal_amount(), orderModel.getPeriod()));
            orderDetailDto.setLimit_price(NumberUtil.formatNumber(limit_price, NumberUtil.FORMAT_4));
            orderDetailDto.setLimit_state(RepaymentReportStatus.PAYMENT_INPROGRESS.getCode());
            orderDetailDto.setCancelable(1);
            //判断订单是否失效
            Long times = Long.parseLong(valid_time);
            if (currentTime.intValue() - times.intValue() > orderModel.getCreate_time().intValue()) {
                orderDetailDto.setLimit_state(RepaymentReportStatus.ORDER_INVALID.getCode());
                orderDetailDto.setCancelable(0);
            }
            this.successData(FrameUtil.newHashMap("data", orderDetailDto,"valid_time",valid_time));
            return;
        }

        // 订单处理中
        if (StagesStatusEnum.MERCHANT_HANDING.getCode() == orderModel.getStatus()) {
            Double limit_price = ArithUtil.round(ArithUtil.div(orderModel.getTotal_amount(), orderModel.getPeriod()));
            orderDetailDto.setLimit_price(NumberUtil.formatNumber(limit_price, NumberUtil.FORMAT_4));
            orderDetailDto.setLimit_state(RepaymentReportStatus.APPLY_SUCCESS.getCode());
            orderDetailDto.setCancelable(1);
            this.successData(FrameUtil.newHashMap("data", orderDetailDto));
            return;
        }

        // 订单已结清
        if (orderModel.getPeriod().intValue() == orderModel.getLimit_pay().intValue()) {
            // 结清状态时，显示总还款+罚息金额
            orderDetailDto.setLimit_price(NumberUtil.formatNumber(ArithUtil.add(orderModel.getInterest_pay(), orderModel.getFine_price()), NumberUtil.FORMAT_4));//已还清时，显示全部已还金额
            orderDetailDto.setLimit_state(RepaymentReportStatus.ALL_CLEAN.getCode());
            this.successData(FrameUtil.newHashMap("data", orderDetailDto));
            return;
        }

        int period = orderModel.getLimit_pay() + 1;
        repaymentDataService.updatePlanByOrder(orderModel, period);
        RepaymentDataModel repaymentDataModel = repaymentDataService.getModelOne(
                FrameUtil.newHashMap("order_id", orderModel.getOrder_id(), "period", period), DbWREnums.READ);

        // 计算罚息金额
        OverdueDto overdueDto = RepaymentUtils.overdueInterest(repaymentDataModel.getRepayment_amount(), repaymentDataModel.getEstimation_repayment_time(), FrameUtil.getTime());
        Double overdue_price = overdueDto.getOverduePrice();

        orderDetailDto.setLimit_price(NumberUtil.formatNumber(ArithUtil.sub(
                ArithUtil.add(repaymentDataModel.getRepayment_amount(), overdue_price),
                repaymentDataModel.getDiscount_amount()), NumberUtil.FORMAT_4));
        orderDetailDto.setOver_time(DateUtil.timestampToDateString(repaymentDataModel.getEstimation_repayment_time(), DateUtil.PATTERN_yyyy_MM_dd));
        orderDetailDto.setOverdue_price(overdue_price);
        orderDetailDto.setOver_day(overdueDto.getOverdueDay());
        orderDetailDto.setRepayment_amount(repaymentDataModel.getRepayment_amount());
        orderDetailDto.setRepayment_id(repaymentDataModel.getId());

        // 取消受理中
        if (StagesStatusEnum.MERCHANT_CONFIRM_CANCEL.getCode() == orderModel.getStatus()) {
            orderDetailDto.setLimit_state(StagesStatusEnum.MERCHANT_CONFIRM_CANCEL.getCode());
            this.successData(FrameUtil.newHashMap("data", orderDetailDto));
            return;
        }

        // 还款开关控制 0 关闭还款功能 1 打开还款功能，在没有配置时默认为关闭状态
        SysParamModel sysParam = SysParamUtil.getSysParamModel(Constant.SysParamKeyEnum.REPAYMENT_SWITCH);
        String repayment_switch = null == sysParam ? "0" : sysParam.getParam_value();

        // 已逾期
        if (repaymentDataModel.getEstimation_repayment_time().longValue() < currentTime) {
            orderDetailDto.setLimit_state(RepaymentReportStatus.OVERDUE.getCode());
            this.successData(FrameUtil.newHashMap("data", orderDetailDto, "repayment_switch", repayment_switch));
            return;
        }

        // 前一期应还款时间（如果是第一期：返回第一期时间，如果大于第一期：返回前一期，月份-1的时间）
        Long prePeriodRepaymentTime = period - 1 < 1 ? repaymentDataModel.getEstimation_repayment_time() : DateUtil.addMonth(repaymentDataModel.getEstimation_repayment_time(), -1);

        if (currentTime < prePeriodRepaymentTime.longValue()) {
            if (orderModel.getLimit_pay().intValue() == 0) {
                // 当期未还清
                orderDetailDto.setLimit_state(RepaymentReportStatus.PERIORD_NONE_CLEAN.getCode());
                // 第一期未还清前，可以取消订单
                if (repaymentDataModel.getPeriod() == 1) {
                    orderDetailDto.setCancelable(1);
                }
            } else {
                // 当期已还清
                orderDetailDto.setLimit_state(RepaymentReportStatus.PERIORD_CLEAN.getCode());
            }
        } else {
            // 当期未还清
            orderDetailDto.setLimit_state(RepaymentReportStatus.PERIORD_NONE_CLEAN.getCode());
            // 第一期未还清前，可以取消订单
            if (repaymentDataModel.getPeriod() == 1) {
                orderDetailDto.setCancelable(1);
            }
        }

        this.successData(FrameUtil.newHashMap("data", orderDetailDto, "repayment_switch", repayment_switch));
    }

}